package com.example.common.utils;

import com.example.common.enums.GlobalExceptionEnum;
import com.example.common.exception.UniversalException;
import org.apache.logging.log4j.util.Strings;
import org.springframework.util.CollectionUtils;

import java.util.Collection;

/**
 * 前置参数校验
 *
 * @author 12071
 * @date 2022/8/9 22:36
 */
public class PreCondition {
    public static void checkArgument(boolean expression) {
        if (!expression) {
            throw UniversalException.build(GlobalExceptionEnum.PARAM_EXCEPTION);
        }
    }

    public static void checkArgument(boolean expression, String message) {
        if (!expression) {
            throw UniversalException.build(GlobalExceptionEnum.PARAM_EXCEPTION.getCode(), message);
        }
    }

    public static void checkArgument(Object obj, String message) {
        if (obj == null) {
            throw UniversalException.build(GlobalExceptionEnum.PARAM_EXCEPTION.getCode(), message);
        }
        if (obj instanceof String) {
            if (Strings.isBlank((String) obj)) {
                throw UniversalException.build(
                        GlobalExceptionEnum.PARAM_EXCEPTION.getCode(), message);
            }
        }
        if (obj instanceof Collection) {
            if (CollectionUtils.isEmpty((Collection) obj)) {
                throw UniversalException.build(
                        GlobalExceptionEnum.PARAM_EXCEPTION.getCode(), message);
            }
        }
    }

    public static void checkArgument(Object obj) {
        if (obj == null) {
            throw UniversalException.build(
                    GlobalExceptionEnum.PARAM_EXCEPTION.getCode(),
                    GlobalExceptionEnum.PARAM_EXCEPTION.getMessage());
        }
        if (obj instanceof String) {
            if (Strings.isBlank((String) obj)) {
                throw UniversalException.build(
                        GlobalExceptionEnum.PARAM_EXCEPTION.getCode(),
                        GlobalExceptionEnum.PARAM_EXCEPTION.getMessage());
            }
        }
        if (obj instanceof Collection) {
            if (CollectionUtils.isEmpty((Collection) obj)) {
                throw UniversalException.build(
                        GlobalExceptionEnum.PARAM_EXCEPTION.getCode(),
                        GlobalExceptionEnum.PARAM_EXCEPTION.getMessage());
            }
        }
    }

    public static void checkArgument(Object obj, RuntimeException e) {
        if (obj == null) {
            throw e;
        }
        if (obj instanceof String) {
            if (Strings.isBlank((String) obj)) {
                throw e;
            }
        }
        if (obj instanceof Collection) {
            if (CollectionUtils.isEmpty((Collection) obj)) {
                throw e;
            }
        }
    }

    public static void checkArgument(boolean b, RuntimeException e) {
        if (!b) {
            throw e;
        }
    }
}
